package es.cazadoresmadridejos.beans.controller.budget;

import javax.servlet.http.HttpServletRequest;

import org.displaytag.pagination.PaginatedList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import es.cazadoresmadridejos.beans.manager.budget.BudgetManager;
import es.cazadoresmadridejos.objs.web.Page;


@Controller
public class BudgetListController {

	@Autowired private BudgetManager budgetManager;

	@RequestMapping(value="/budgetList*.html")
	public ModelAndView list(
			HttpServletRequest request,
			Boolean isList
			) throws Throwable {

		ModelAndView mv;
		if(Boolean.TRUE.equals(isList)){
			mv = new ModelAndView("budgetList");
		}else{
			mv = new ModelAndView();
		}		

		PaginatedList list = budgetManager.findAllPaginated(new Page(request));

		mv.addObject("list", list);

		return mv;
	}


	@RequestMapping(value="/budgetDelete.html")
	public ModelAndView delete(
			@RequestParam(value="id")Long id,
			HttpServletRequest request
			) throws Throwable {

		budgetManager.delete(id);

		return list(request,true);
	}

//	@RequestMapping(value="/budgetDownload.html")
//	public void download(
//			@RequestParam(value="id")Long id,
//			HttpServletRequest request,
//			HttpServletResponse response
//			) throws Throwable {
//		OutputStream out = response.getOutputStream();
//
//		Budget budget = budgetManager.get(id);
//		String root = System.getProperty("catalina.home") + File.separator + FileType.ADVICED.toString() + File.separator;
//		File file = new File(root + budget.getImageUrl());
//
//		int index = budget.getImageUrl().lastIndexOf(".");
//		String ext = budget.getImageUrl().substring(index);
//
//		response.setContentType( "application/x-download" );
//		response.setHeader( "Content-Disposition", "attachment; filename=" + budget.getTitle() + ext);
//		response.setContentLength( (int)file.length() );
//
//		byte[] bbuf = new byte[1024];
//		DataInputStream in = new DataInputStream(new FileInputStream(file));
//		int length; 
//
//		while ((in != null) && ((length = in.read(bbuf)) != -1))
//		{
//			out.write(bbuf,0,length);
//		}
//
//		in.close();
//		out.flush();
//		out.close();		
//	}


}
